var modelList = [];
var modelListLength;
var currIndex = 0;
var messageJson = [];
var messageJsonLength;
var changeModelInterval;
var isCancelAutoChangeModel = false;
var autoChangeMilliseconds = 300000;

function changeBg(bgUrl) {
    if (bgUrl != undefined) {
        $("#landlord").css({ "background-image": "url(" + bgUrl + ")" });
        $("#landlord").addClass("bgDiv");
    }else{
        $("#landlord").css({ "background-image": ""});
        $("#landlord").removeClass("bgDiv");
    }
}

function initModel() {
    initModelList();
    initLive2d();
    initTips();
    window.setInterval(showHitokoto, 10000);
    changeModelInterval = window.setInterval(autoChangeModel, autoChangeMilliseconds);
}

function autoChangeModel() {
    if (modelListLength > 1) {
        changeModel();
    }
}

function changeModel() {
    currIndex = currIndex + 1;
    console.log(modelListLength);
    if (currIndex >= modelListLength) {
        currIndex = 0;
    }
    console.log(currIndex);
    let modelItem = modelList[currIndex];
    console.log(modelItem);
    let modelPath = modelItem.modelPath;
    loadlive2d("live2d", modelPath);
    let bgUrl = modelItem.bgUrl;
    console.log(bgUrl);
    changeBg(bgUrl);
}


function initModelList() {
    $.ajax({
        cache: true,
        url: './live2d/modelList.json',
        dataType: "json",
        success: function (result) {
            modelList = result.modelList;
            modelListLength = modelList.length;
            console.log(modelList);
            console.log(modelList.length);
            let modelItem = modelList[0];
            let modelPath = modelItem.modelPath;
            let bgUrl = modelItem.bgUrl;
            console.log(bgUrl);
            changeBg(bgUrl);
            loadlive2d("live2d", modelPath);
        }
    });
}


function closeApp() {
    try {
        var ipcRender = require('electron').ipcRenderer
        ipcRender.send('handelClose', "执行关闭")
    }
    catch (e) {
        console.log("不支持ipcRenderer")
    }
}


function OpenDefaultBrowser(url) {
    try {
        var ipcRender = require('electron').ipcRenderer
        ipcRender.send('open-url', url)
    }
    catch (e) {
        console.log("不支持ipcRenderer")
    }
}

function initLive2d() {
    $('.fui-home').click(function () {
        OpenDefaultBrowser("http://39.106.104.78:8080/blog/");
    });
    $('.live2d-tool .fui-chat').click(function () {
        showHitokoto();
    });
    $('.live2d-tool .fui-photo').click(function () {
        showMessage('照好了嘛，是不是很可爱呢？', 5000, true);
        window.Live2D.captureName = 'Live2D.png';
        window.Live2D.captureFrame = true;
    });
    $('.fui-cross').click(function () {
        closeApp();
    });

    $('.fui-eye').click(function () {
        if (isCancelAutoChangeModel) {
            isCancelAutoChangeModel = false;
        } else {
            isCancelAutoChangeModel = true;
        }
        if (isCancelAutoChangeModel) {
            window.clearInterval(changeModelInterval);
            showMessage('关闭自动切换模型', 5000);
        } else {
            changeModelInterval = window.setInterval(autoChangeModel, autoChangeMilliseconds);
            showMessage('开启自动切换模型，切换时间间隔是:' + autoChangeMilliseconds / 1000 + '秒', 5000);
        }
    });

    $('.fui-user').click(function () {
        changeModel();
    });
}

function renderTip(template, context) {
    var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
    return template.replace(tokenReg, function (word, slash1, token, slash2) {
        if (slash1 || slash2) {
            return word.replace('\\', '');
        }
        var variables = token.replace(/\s/g, '').split('.');
        var currentObject = context;
        var i, length, variable;
        for (i = 0, length = variables.length; i < length; ++i) {
            variable = variables[i];
            currentObject = currentObject[variable];
            if (currentObject === undefined || currentObject === null) return '';
        }
        return currentObject;
    });
}

String.prototype.renderTip = function (context) {
    return renderTip(this, context);
};

function initTips() {
    $.ajax({
        cache: true,
        url: './live2d/message.json',
        dataType: "json",
        success: function (result) {
            $.each(result.mouseover, function (index, tips) {
                $(tips.selector).mouseover(function () {
                    var text = tips.text;
                    if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
                    text = text.renderTip({ text: $(this).text() });
                    showMessage(text, 3000);
                });
            });
            $.each(result.click, function (index, tips) {
                $(tips.selector).click(function () {
                    var text = tips.text;
                    if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
                    text = text.renderTip({ text: $(this).text() });
                    showMessage(text, 3000);
                });
            });
            messageJson = result.messageJson;
            messageJsonLength = messageJson.length;
        }
    });
}

(function () {
    var text;
    var now = (new Date()).getHours();
    if (now > 23 || now <= 5) {
        text = '你是夜猫子呀？这么晚还不睡觉，明天起的来嘛？';
    } else if (now > 5 && now <= 7) {
        text = '早上好！一日之计在于晨，美好的一天就要开始了！';
    } else if (now > 7 && now <= 11) {
        text = '上午好！工作顺利嘛，不要久坐，多起来走动走动哦！';
    } else if (now > 11 && now <= 14) {
        text = '中午了，工作了一个上午，现在是午餐时间！';
    } else if (now > 14 && now <= 17) {
        text = '午后很容易犯困呢，今天的运动目标完成了吗？';
    } else if (now > 17 && now <= 19) {
        text = '傍晚了！窗外夕阳的景色很美丽呢，最美不过夕阳红~~';
    } else if (now > 19 && now <= 21) {
        text = '晚上好，今天过得怎么样？';
    } else if (now > 21 && now <= 23) {
        text = '已经这么晚了呀，早点休息吧，晚安~~';
    } else {
        text = '嗨~ 快来逗我玩吧！';
    }
    showMessage(text, 12000);
})();

function showHitokoto() {
    var messageText = messageJson[Math.floor(Math.random() * messageJsonLength)].text;
    showMessage(messageText, 5000);
}

function showMessage(text, timeout) {
    if (Array.isArray(text)) text = text[Math.floor(Math.random() * text.length + 1) - 1];
    //console.log('showMessage', text);
    $('.live2d-tips').stop();
    $('.live2d-tips').html(text).fadeTo(200, 1);
    if (timeout === null) timeout = 5000;
    hideMessage(timeout);
}

function hideMessage(timeout) {
    $('.live2d-tips').stop().css('opacity', 1);
    if (timeout === null) timeout = 5000;
    $('.live2d-tips').delay(timeout).fadeTo(200, 0);
}

